home *** CD-ROM | disk | FTP | other *** search
/ Tech Arsenal 1 / Tech Arsenal (Arsenal Computer).ISO / tek-01 / strlib.zip / STR2INT.C < prev    next >
Text File  |  1993-01-04  |  7KB  |  181 lines

  1.  
  2. /*  File   : str2int.c
  3.     Author : Richard A. O'Keefe
  4.     Updated: 27 April 1984
  5.     Defines: str2int(), atoi(), atol()
  6.  
  7.     str2int(src, radix, lower, upper, &val)
  8.     converts the string pointed to by src to an integer and stores it in
  9.     val.  It skips leading spaces and tabs (but not newlines, formfeeds,
  10.     backspaces), then it accepts an optional sign and a sequence of digits
  11.     in the specified radix.  The result should satisfy lower <= *val <= upper.
  12.     The result is a pointer to the first character after the number;
  13.     trailing spaces will NOT be skipped.
  14.  
  15.     If an error is detected, the result will be NullS, the value put
  16.     in val will be 0, and errno will be set to
  17.         EDOM    if there are no digits
  18.         ERANGE  if the result would overflow or otherwise fail to lie
  19.                 within the specified bounds.
  20.     Check that the bounds are right for your machine.
  21.     This looks amazingly complicated for what you probably thought was an
  22.     easy task.  Coping with integer overflow and the asymmetric range of
  23.     twos complement machines is anything but easy.
  24.  
  25.     So that users of atoi and atol can check whether an error occured,
  26.     I have taken a wholly unprecedented step: errno is CLEARED if this
  27.     call has no problems.
  28. */
  29.  
  30. #include "strings.h"
  31. #include "ctypes.h"
  32. #include <errno.h>
  33. extern int errno;
  34.  
  35. /*      CHECK THESE CONSTANTS FOR YOUR MACHINE!!!       */
  36.  
  37. #if     pdp11
  38. #   define      MaxInt      0x7fffL     /* int  = 16 bits */
  39. #   define      MinInt      0x8000L
  40. #   define      MaxLong 0x7fffffffL     /* long = 32 bits */
  41. #   define      MinLong 0x80000000L
  42. #else  !pdp11
  43. #   define      MaxInt  0x7fffffffL     /* int  = 32 bits */
  44. #   define      MinInt  0x80000000L
  45. #   define      MaxLong 0x7fffffffL     /* long = 32 bits */
  46. #   define      MinLong 0x80000000L
  47. #endif  pdp11
  48.  
  49.  
  50. char *str2int(src, radix, lower, upper, val)
  51.     register char *src;
  52.     register int radix;
  53.     long lower, upper, *val;
  54.     {
  55.         int sign;               /* is number negative (+1) or positive (-1) */
  56.         int n;                  /* number of digits yet to be converted */
  57.         long limit;             /* "largest" possible valid input */
  58.         long scale;             /* the amount to multiply next digit by */
  59.         long sofar;             /* the running value */
  60.         register int d;         /* (negative of) next digit */
  61.         char *answer;
  62.  
  63.         /*  Make sure *val is sensible in case of error  */
  64.  
  65.         *val = 0;
  66.  
  67.         /*  Check that the radix is in the range 2..36  */
  68.  
  69.         if (radix < 2 || radix > 36) {
  70.             errno = EDOM;
  71.             return NullS;
  72.         }
  73.  
  74.         /*  The basic problem is: how do we handle the conversion of
  75.             a number without resorting to machine-specific code to
  76.             check for overflow?  Obviously, we have to ensure that
  77.             no calculation can overflow.  We are guaranteed that the
  78.             "lower" and "upper" arguments are valid machine integers.
  79.             On sign-and-magnitude, twos-complement, and ones-complement
  80.             machines all, if +|n| is representable, so is -|n|, but on
  81.             twos complement machines the converse is not true.  So the
  82.             "maximum" representable number has a negative representative.
  83.             Limit is set to min(-|lower|,-|upper|); this is the "largest"
  84.             number we are concerned with.       */
  85.  
  86.         /*  Calculate Limit using Scale as a scratch variable  */
  87.  
  88.         if ((limit = lower) > 0) limit = -limit;
  89.         if ((scale = upper) > 0) scale = -scale;
  90.         if (scale < limit) limit = scale;
  91.  
  92.         /*  Skip leading spaces and check for a sign.
  93.             Note: because on a 2s complement machine MinLong is a valid
  94.             integer but |MinLong| is not, we have to keep the current
  95.             converted value (and the scale!) as *negative* numbers,
  96.             so the sign is the opposite of what you might expect.
  97.             Should the test in the loop be isspace(*src)?
  98.         */
  99.         while (*src == ' ' || *src == '\t') src++;
  100.         sign = -1;
  101.         if (*src == '+') src++; else
  102.         if (*src == '-') src++, sign = 1;
  103.  
  104.         /*  Check that there is at least one digit  */
  105.  
  106.         if (_c2type[1+ *src] >= radix) {
  107.             errno = EDOM;
  108.             return NullS;
  109.         }
  110.  
  111.         /*  Skip leading zeros so that we never compute a power of radix
  112.             in scale that we won't have a need for.  Otherwise sticking
  113.             enough 0s in front of a number could cause the multiplication
  114.             to overflow when it neededn't.
  115.         */
  116.         while (*src == '0') src++;
  117.  
  118.         /*  Move over the remaining digits.  We have to convert from left
  119.             to left in order to avoid overflow.  Answer is after last digit.
  120.         */
  121.         for (n = 0; _c2type[1+ *src++] < radix; n++) ;
  122.         answer = --src;
  123.  
  124.         /*  The invariant we want to maintain is that src is just
  125.             to the right of n digits, we've converted k digits to
  126.             sofar, scale = -radix**k, and scale < sofar < 0.  Now
  127.             if the final number is to be within the original
  128.             Limit, we must have (to the left)*scale+sofar >= Limit,
  129.             or (to the left)*scale >= Limit-sofar, i.e. the digits
  130.             to the left of src must form an integer <= (Limit-sofar)/(scale).
  131.             In particular, this is true of the next digit.  In our
  132.             incremental calculation of Limit,
  133.  
  134.                 IT IS VITAL that (-|N|)/(-|D|) = |N|/|D|
  135.         */
  136.  
  137.         for (sofar = 0, scale = -1; --n >= 0; ) {
  138.             d = _c2type[1+ *--src];
  139.             if (-d < limit) {
  140.                 errno = ERANGE;
  141.                 return NullS;
  142.             }
  143.             limit = (limit+d)/radix, sofar += d*scale;
  144.             if (n != 0) scale *= radix; /* watch out for overflow!!! */
  145.         }
  146.         /*  Now it might still happen that sofar = -32768 or its equivalent,
  147.             so we can't just multiply by the sign and check that the result
  148.             is in the range lower..upper.  All of this caution is a right
  149.             pain in the neck.  If only there were a standard routine which
  150.             says generate thus and such a signal on integer overflow...
  151.             But not enough machines can do it *SIGH*.
  152.         */
  153.         if (sign < 0 && sofar < -MaxLong /* twos-complement problem */
  154.         ||  (sofar*=sign) < lower || sofar > upper) {
  155.             errno = ERANGE;
  156.             return NullS;
  157.         }
  158.         *val = sofar;
  159.         errno = 0;              /* indicate that all went well */
  160.         return answer;
  161.     }
  162.  
  163.  
  164. int atoi(src)
  165.     char *src;
  166.     {
  167.         long val;
  168.         str2int(src, 10, MinInt, MaxInt, &val);
  169.         return (int)val;
  170.     }
  171.  
  172.  
  173. long atol(src)
  174.     char *src;
  175.     {
  176.         long val;
  177.         str2int(src, 10, MinLong, MaxLong, &val);
  178.         return val;
  179.     }
  180.  
  181.